package com.unipay.system.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.unipay.common.result.JwtHelper;
import com.unipay.common.result.MD5;
import com.unipay.common.result.Result;
import com.unipay.common.result.ResultCodeEnum;
import com.unipay.model.system.SysUser;
import com.unipay.model.vo.LoginVo;
import com.unipay.system.handler.UnipayException;
import com.unipay.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: unipay-auth-parent
 * @Author: cmy
 * @CreateTime: 2023-02-05  16:39
 * @Description: TODO 整合前端，登录登出
 *
 *      接口处理完后，修改对应前端接口：/system-front/src/api/user.js
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    /*
     * 1、登录
     *  headers：
     *      Request URL: http://localhost:9528/dev-api/vue-admin-template/user/login
     *      Request method: POST
     *  response：
     *      {"code":20000,"data":{"token":"admin-token"}}
     **/
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        //（1）根据username查询数据
        SysUser sysUser = sysUserService.getInfoByUsername(loginVo.getUsername());
        //（2）查询为空，抛出异常；否则，继续判断
        if (sysUser == null){
            throw new UnipayException(20001, "该用户不存在！！！");
        }
        //（3）用户名，是否存在、可用
        if (sysUser.getStatus().intValue() == 0){
            throw new UnipayException(ResultCodeEnum.ACCOUNT_STOP.getCode(), ResultCodeEnum.ACCOUNT_STOP.getMessage());
        }
        //（4）判断：密码是否正确
        // 先加密MD5
        String encryptPassword = MD5.encrypt(loginVo.getPassword());
        if (!encryptPassword.equals(sysUser.getPassword())){
            throw new UnipayException(20001, "密码错误...");
        }
        //（5）根据userid和username生成token字符串，通过map返回
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    //
    /*
     * 1.2、返回的“用户信息”
     *  headers：
     *      Request URL: http://localhost:9528/dev-api/vue-admin-template/user/info?token=admin-token
     *      Request method: GET
     *  response：{
     *      "code":20000,
     *      "data":{
     *          "roles":["admin"],
     *          "introduction":"I am a super administrator",
     *          "avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
     *          "name":"Super Admin"
     *      }
     *  }
     * public Result logInfo(){
     *      HashMap<String, Object> map = new HashMap<>();
            map.put("roles", "[\"admin\"]");
            map.put("introduction", "I am a super administrator");
            map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            map.put("name", "Unipay Admin");
            return Result.ok(map);
        }
        *   TODO 获取用户信息：
        *    主要是获取当前登录用户的 “菜单权限”及 “按钮权限”数据
     **/
    @ApiOperation(value = "登录用户信息")
    @GetMapping("/info")
    public Result logInfo(HttpServletRequest request){
        //（1）获取“请求头”，token字符串
        String token = request.getHeader("token");
        //（2）从token字符串，获取用户名称（id）
        String username = JwtHelper.getUsername(token);
        //（3）根据用户名称，获取用户信息：基本信息、菜单权限、按钮权限
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }
/*
{
  "code": 200,
  "message": "成功",
  "data": {
    "buttons": null,
    "roles": "[\"admin\"]",
    "name": "admin",
    "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
    "routers": [
      {
        "path": "/system",
        "hidden": false,
        "component": "Layout",
        "alwaysShow": true,
        "meta": {
          "title": "系统管理",
          "icon": "el-icon-s-tools"
        },
        "children": [
          {
            "path": "sysUser",
            "hidden": false,
            "component": "system/sysUser/list",
            "alwaysShow": false,
            "meta": {
              "title": "用户管理",
              "icon": "el-icon-s-custom"
            },
            "children": null
          },
          {
            "path": "assignAuth",
            "hidden": true,
            "component": "system/sysRole/assignAuth",
            "alwaysShow": false,
            "meta": {
              "title": "分配权限",
              "icon": null
            },
            "children": null
          },
          {
            "path": "sysRole",
            "hidden": false,
            "component": "system/sysRole/list",
            "alwaysShow": false,
            "meta": {
              "title": "角色管理",
              "icon": "el-icon-user-solid"
            },
            "children": null
          },
          {
            "path": "sysMenu",
            "hidden": false,
            "component": "system/sysMenu/list",
            "alwaysShow": false,
            "meta": {
              "title": "菜单管理",
              "icon": "el-icon-s-unfold"
            },
            "children": null
          },
          {
            "path": "sysDept",
            "hidden": false,
            "component": "system/sysDept/list",
            "alwaysShow": false,
            "meta": {
              "title": "部门管理",
              "icon": "el-icon-s-operation"
            },
            "children": null
          },
          {
            "path": "sysPost",
            "hidden": false,
            "component": "system/sysPost/list",
            "alwaysShow": false,
            "meta": {
              "title": "岗位管理",
              "icon": "el-icon-more-outline"
            },
            "children": null
          },
          {
            "path": "log",
            "hidden": false,
            "component": "ParentView",
            "alwaysShow": true,
            "meta": {
              "title": "日志管理",
              "icon": "el-icon-tickets"
            },
            "children": [
              {
                "path": "",
                "hidden": false,
                "component": "",
                "alwaysShow": false,
                "meta": {
                  "title": "test",
                  "icon": "el-icon-info"
                },
                "children": null
              },
              {
                "path": "sysOperLog",
                "hidden": false,
                "component": "system/sysOperLog/list",
                "alwaysShow": false,
                "meta": {
                  "title": "操作日志",
                  "icon": "el-icon-document-remove"
                },
                "children": null
              },
              {
                "path": "sysLoginLog",
                "hidden": false,
                "component": "system/sysLoginLog/list",
                "alwaysShow": false,
                "meta": {
                  "title": "登录日志",
                  "icon": "el-icon-s-goods"
                },
                "children": null
              }
            ]
          }
        ]
      }
    ]
  }
}
 */


    /*
     * 3、退出登录（方法1：后端写方法，调度； 方法2：通过修改前端，）
     *  headers：
     *      Request URL: http://localhost:9528/dev-api/vue-admin-template/user/logout
     *      Request method: POST
     *  response：
     *      {"code":20000,"data":"success"}
     **/
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();     // 默认返回：{"code":200,"message":"成功","data":null}
    }
}
